package com.nulldev.util.uri.yt.extraction;

import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.regex.Pattern;

import com.nulldev.util.java.JVMUtil;
import com.nulldev.util.math.MathUtil;
import com.nulldev.util.other.ArrayUtils;
import com.nulldev.util.other.CharsetUtil;
import com.nulldev.util.string.StringsUtil;
import com.nulldev.util.uri.URIUtil;
import com.nulldev.util.uri.Soup_imported.Jsoup;
import com.nulldev.util.uri.Soup_imported.nodes.Document;
import com.nulldev.util.uri.Soup_imported.nodes.Element;
import com.nulldev.util.uri.Soup_imported.select.Elements;

/**
 * WORK IN PROGRESS
 * @author null
 */
public class YouTubeSearch {
	
	public static enum SearchResultType {
		VIDEO("video"),
		PLAYLIST("playlist"),
		CHANNEL("channel")
		
		;
		
		private final String data;
		private SearchResultType(final String data) {
			this.data = data;
		}
		
		public String getDataString() {
			return this.data;
		}
	}

	public static class SearchResult {
		private final String title, url, thumbURL;
		private final long duration;
		private final SearchResultType type;
		
		public SearchResult(final String title, final String url, final String thumbURL,
				final long duration, final SearchResultType type) {
			this.title = title;
			this.url = url;
			this.thumbURL = thumbURL;
			this.duration = duration;
			this.type = type;
		}
		
		public String getTitle() {
			return this.title;
		}
		
		public String getURL() {
			return this.url;
		}
		
		public String getThumbURL() {
			return this.thumbURL;
		}
		
		public long duration() {
			return this.duration;
		}

		public SearchResultType getType() {
			return this.type;
		}
	}
	
	public static LinkedList<SearchResult> get(final String term) {
		final LinkedList<SearchResult> results = new LinkedList<SearchResult>();
		try {
			final String encoded_term = URLEncoder.encode(term, CharsetUtil.UTF_8.name());
			final String url0 = "https://www.youtube.com/results?search_query=" + encoded_term;
			final String pageData = URIUtil.downloadPage(URIUtil.safeCreate(url0));
			final Document doc = Jsoup.parse(pageData);
			// search results
			final Elements e0 = doc.getElementsByClass("item-section");
			if (e0 == null || e0.size() == 0) {
				return results;
			}
			final Element e = e0.get(0);
			for (final Element li : e.children()) {
				final boolean isAd = li.child(0).className().equals("pyv-afc-ads-container");
				if (isAd) { 
					continue;
				}else {
					if (li.child(0).className().contains("yt-lockup-channel")) {
						final Element core = li.child(0);
						//JVMUtil.async_println(core.html());
						final String corecStr = core.child(0).child(0).attr("href");
						final String channelURL = "/channel?c=" + ArrayUtils.last(corecStr.split(Pattern.quote("channel/")));
						final String channelName = core.child(1).child(0).child(0).text();
						String thumbnail = "https:" + core.child(0).child(0).child(0).child(0).child(0).attr("src");
						if (thumbnail.contains("yts") && thumbnail.endsWith(".gif")) {
							thumbnail = "https:" + core.child(0).child(0).child(0).child(0).child(0).attr("data-thumb");
						}
						if (thumbnail.startsWith("https:https://")) {
							thumbnail = "https://" + thumbnail.substring("https:https://".length());
						}
						final long time = 0;
						results.add(new SearchResult(channelName, channelURL, 
								thumbnail, time, SearchResultType.CHANNEL));
					}else { 
						try {
							final Element core = li.child(0).child(0);
							final Element thumbEle = core.child(0).child(0).child(0).child(0).child(0);
							String thumbURL = thumbEle.attr("src");
							if (thumbURL.startsWith("/yts/img/pixel-") && thumbURL.endsWith(".gif")) {
								thumbURL = thumbEle.attr("data-thumb");
							}
							final Element data = core.child(1);
							final String title = data.child(0).child(0).attr("title").split("  - ")[0];
							final String timePre1 = data.child(0).child(0).attr("title").split("  - ")[1];
							final String timePre = StringsUtil.substringBetween(timePre1, ": ", ".");
							long time = MathUtil.TimeToSeconds.parseTimeStringToSeconds(timePre);
							if (time == 0 && data.child(0).children().size() > 1) {
								final String timePre1_f = data.child(0).child(1).attr("title").split("  - ")[1];
								final String timePre_f = StringsUtil.substringBetween(timePre1_f, ": ", ".");
								time = MathUtil.TimeToSeconds.parseTimeStringToSeconds(timePre_f);
							}
							final String url = data.child(0).child(0).attr("href");
							SearchResultType type = SearchResultType.VIDEO;
							if (url.contains("&list=")) {
								type = SearchResultType.PLAYLIST;
							}
							results.add(new SearchResult(title, url, thumbURL, time, type));
						}catch (IndexOutOfBoundsException e00) {
						}catch (Exception e00) {
							e00.printStackTrace();
						}
					}
				}
			}
//			ArrayUtils.printLln(e);
//			for (final Element ed : e.getElementsByTag("ytd-video-renderer")) {
//				final Element vd = ed.getElementById("dismissable");
//				final Element thumb_root = vd.getElementById("thumbnail");
//				final String link = thumb_root.attr("href");
//				final String thumb = thumb_root.getElementById("img").attr("src");
//				System.out.println("link=" + link);
//				System.out.println("thumb=" + thumb);
//			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return results;
	}
}
